/*
 *
 *  Copyright (C) 2010 GSyC/LibreSoft, Universidad Rey Juan Carlos.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Raúl Román López <rroman@gsyc.es>
 *
 */

package com.LibreGeoSocial.App.AR;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.Toast;

import com.LibreGeoSocial.Api.LibreGeoSocial;
import com.LibreGeoSocial.Api.Layers.GenericLayer;
import com.LibreGeoSocial.Api.Layers.LibreGeoSocialLayer;
import com.LibreGeoSocial.Api.Layers.NodeListLayer;
import com.LibreGeoSocial.Api.Layers.PanoramioLayer;
import com.LibreGeoSocial.Api.Layers._11870Layer;
import com.LibreGeoSocial.App.DataManager;
import com.LibreGeoSocial.App.LocationWays;
import com.LibreGeoSocial.App.R;
import com.LibreGeoSocial.App.AR.Overlays.CamPreview;
import com.LibreGeoSocial.App.AR.Overlays.CustomViews;
import com.LibreGeoSocial.App.AR.Overlays.DrawFocus;
import com.LibreGeoSocial.App.AR.Overlays.DrawParameters;
import com.LibreGeoSocial.App.AR.Overlays.DrawPath;
import com.LibreGeoSocial.App.AR.Overlays.DrawRadar;
import com.LibreGeoSocial.App.ARTesting.TestingManager;
import com.LibreGeoSocial.App.GeoNames.AltitudeManager;
import com.LibreGeoSocial.App.Routes.ILocationServiceListener;
import com.LibreGeoSocial.App.Routes.LocationService;
import com.LibreGeoSocial.App.Utils.LocationUtils;

public class ARView extends ARActivity{ 
	private static final int MENU_TAGGING = Menu.FIRST + 1;
	private static final int MENU_TAGGING_IMMEDIATE = MENU_TAGGING + 1;
	private static final int MENU_TAGGING_FAST = MENU_TAGGING_IMMEDIATE + 1;
	private static final int MENU_TAGGING_MAP = MENU_TAGGING_FAST + 1;
	private static final int MENU_TAGGING_ACCURATE_SIDE = MENU_TAGGING_MAP + 1;
	private static final int MENU_TAGGING_ACCURATE_LINE = MENU_TAGGING_ACCURATE_SIDE + 1;
	private static final int MENU_TAGGING_ANGLE = MENU_TAGGING_ACCURATE_LINE + 1;
	
	private static final int MENU_DISTANCE_FILTER = MENU_TAGGING_ANGLE + 1;
	
	private static final int MENU_COMPASS_CORRECTION = MENU_DISTANCE_FILTER + 1;
	
	private static final int MENU_LOCATION = MENU_COMPASS_CORRECTION + 1;
	private static final int MENU_INDOOR_LOCATION = MENU_LOCATION + 1;
	private static final int MENU_SERVICE_LOCATION = MENU_INDOOR_LOCATION + 1;
	private static final int MENU_LOCATION_WAYS = MENU_SERVICE_LOCATION + 1;
	
	private static final int MENU_PREFERENCES = MENU_LOCATION_WAYS + 1;
	
	public static final int DIALOG_MOVE = 0;
	private static final int DIALOG_PBAR = 1;
	private static final int DIALOG_NOHEIGHT = 2;
	
	private static final int BIDI_LOC = 20;
	private static final int LOC_WAYS = 21;
	
	private static final int ACTION_NOHEIGHT = 0;
	private static final int ACTION_IGNORE = 1;
	private static final int ACTION_REQUEST = 2;
	
	private static ARView pointerObject = null;
	
	protected PowerManager.WakeLock mWakeLock;
	
    private CamPreview mPreview;
    private DrawParameters mParameters;
    private DrawFocus mFocus;
    private DrawRadar mRadar;
    private DrawPath mPath;
    
    private int action = -1;
    
    //FIXME Open GL part
//    private GLSurfaceView opengl;
//    private CubeRenderer cubeList;
    ////////////////////
    
    private float cam_altitude;
    private float altitude;
//    private static float res_values[] = new float[3];
    private ARCompassManager compassManager;
    private int idGPS = -1;
    private static boolean showMenu = true;
    
    private boolean refreshed;
    private boolean load_list = true;
    private static ARTagManager tagManager; 
    
    private String[] strCategories = null;
	
	private ARCompassManager.OnCompassChangeListener compassListener = new ARCompassManager.OnCompassChangeListener(){

		public void onChange(float[] values) {
			
			float[] values_new = values.clone();

			//THIS PART IS CRITICAL IN ORDER TO REFRESH THE VIEW!!!
			if(mParameters!=null){
				mParameters.setValues(values_new, getLocation(), cam_altitude);
				mParameters.invalidate();
			}

			if(mRadar!=null){
				mRadar.setAzimuth(ARCompassManager.getAzimuth(values_new));
			}

//			if(mPath!=null){
////				mPath.setInclination(ARCompassManager.getAzimuth(values_new));
//				mArrow.setAzimuth(values_new[2]);
//				mPath.invalidate();
//			}

			if (refreshed)
				refreshResourceDrawns(values_new);
			
			if(tagManager != null)
				tagManager.setAngles(values_new);
		}
		
	};
	
	OnClickListener distFiltClickListener = new OnClickListener() {
		
		public void onClick(View v) {
			refreshed = false;
			showMenu = true;
			
			getMyLayer().setDistance(CustomViews.getSeekbarValue());
    		getLayers().removeExtraElement((View) v.getParent());
    		getLayers().cleanResouceLayer();
			load_list = true;
			showResources();
		}
	};
	
    ILocationServiceListener locationListener = new ILocationServiceListener(){

		public void updateCurrentLocation(Location loc) {
			
			float[] location = {(float) loc.getLatitude(), (float) loc.getLongitude(), 0};
			setLocation(location);
			
			SharedPreferences sharedPreferences = 
				PreferenceManager.getDefaultSharedPreferences(ARView.this);
			if(sharedPreferences.getBoolean(ARPreferences.KEY_GPS, true))
				altitude = (float) loc.getAltitude();
			else
				if(tagManager.getSavingType() == -1)
					altitude = (float) AltitudeManager.getAltitudeFromLatLong(getLocation()[0], getLocation()[1]);
			cam_altitude = AltitudeManager.getAbsoluteAltitude(ARView.this, altitude, true);
			LocationUtils.setUserHeight(cam_altitude);
			if(tagManager != null){
				tagManager.setUserLocation(location);
				tagManager.setCamAltitude(cam_altitude);
			}
		}
    	
    };
    
//    private OnClickListener acceptCorrection = new OnClickListener() {
//		public void onClick(View v) {
//			compassManager.setCorrection(ARView.this, (float)CustomViews.getSeekbarValue());
//			getLayers().removeExtraElement((View) v.getParent());
//			showMenu = true;
//		}
//	};
	
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        try {

            pointerObject = this;
			refreshed = false;
        	
        	showMenu = true;
        	
			float[] location = new float[3];
			location[0] =  (float) LocationService.getCurrentLocation().getLatitude();
			location[1] = (float) LocationService.getCurrentLocation().getLongitude();
			setLocation(location);
			altitude = (float) LocationService.getCurrentLocation().getAltitude();
			cam_altitude = AltitudeManager.getAbsoluteAltitude(getBaseContext(), altitude, true);
			LocationUtils.setUserHeight(cam_altitude);
			
			// Hide the window title.
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			
			// Create our Preview view and set it as the content of our activity.
			mPreview = new CamPreview(this);
			
			// setting the layers which we use as graphical containers
			getLayers().setBaseLayer(mPreview);
//			layers.addBaseLayer(mPreview);
			getLayers().setInfoLayer();
			getLayers().setResourceLayer();
			getLayers().setExtraLayer();
			
			mFocus = new DrawFocus(this);
			mRadar = new DrawRadar(this);
			
			getLayers().addInfoElement(mRadar, null);
			getLayers().addInfoElement(mFocus, null);
			
			SharedPreferences sharedPreferences = 
				PreferenceManager.getDefaultSharedPreferences(ARView.this);
//			if(sharedPreferences.getBoolean(ARPreferences.KEY_MOVEMENT_LINE, false)){
//				mPath = new DrawPath(this);
//				getLayers().addInfoElement(mPath, null);
//			}
			
			if(sharedPreferences.getBoolean(ARPreferences.KEY_MEASURES, false)){
				mParameters = new DrawParameters(this);
				getLayers().addInfoElement(mParameters, null);
			}
			
			tagManager = new ARTagManager(this, getLayers());
			tagManager.setSavingType(-1);
			tagManager.setUserLocation(getLocation());
			tagManager.setCamAltitude(cam_altitude);
			
			getLayers().setMoveSummary(sharedPreferences.getBoolean(ARPreferences.KEY_MOVE_LABELS, false));
   
			final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
			this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "My Tag");
			this.mWakeLock.acquire();
			
			
			if(getMyLayer() == null)
				setMyLayer((GenericLayer) DataManager.getInstance().getData(DataManager.GENERIC_LAYER));
			
    		if (strCategories==null)
	        	strCategories = (String[]) DataManager.getInstance().getData(DataManager.LAYER_CATEGORIES);
			
			compassManager = new ARCompassManager(this);
			
			if (getMyLayer().getNodes() != null)
				load_list = false;
			
		} catch (Exception e) {
			Toast.makeText(getBaseContext(), 
					e.toString(), 
					Toast.LENGTH_LONG).show();
		}
        
        
    }
    
    private void showResources(){
    	refreshed = false;

		getLayers().removeSummaryBox();

		setResourcesList(null);
    	if(!load_list){
    		
    		ArrayList<ARGeoNode> res_list;
    		
    		res_list = ARUtils.cleanNoLocation(this, getLayers(), getMyLayer().getNodes());
    		
    		if(res_list == null){
    			Toast.makeText(getBaseContext(), 
    					"No resources available", 
    					Toast.LENGTH_LONG).show();
        		load_list = true;
        		return;
    		}
    		
    		if (res_list.size() > 50){
    			ArrayList<ARGeoNode> list = (ArrayList<ARGeoNode>) res_list.clone();
    			res_list.clear();
    			for(int i = 0; i < 50; i++)
    				res_list.add(list.get(i));
    			Toast.makeText(getBaseContext(), 
    					"Too many objects, showing the first 50 ones", 
    					Toast.LENGTH_LONG).show();
    		}
    		
    		ARGeoNodeAzimuthComparator comparator = new ARGeoNodeAzimuthComparator();
    		Collections.sort(res_list, comparator);
    		
    		setResourcesList(res_list);
    		
    		mRadar.setResourcesList(res_list);
    		
    		boolean no_height = false;
    		if(isUsingHeight())
    			no_height = ARUtils.checkNoAltitudeInfo(res_list);
    		
    		load_list = true;
        	refreshed = true;
        	
        	if((no_height) && (action < 0))
        		showDialog(DIALOG_NOHEIGHT);
        	else{
        		switch(action){
        		case ACTION_REQUEST:
        			if(loadMainHeightPreference())
        				actionRequestHeight();
        			break;
        		case ACTION_NOHEIGHT:
        			useHeight(false);
        			break;
        		case ACTION_IGNORE:
        			break;
        		default:
        			break;
        		}
        	}
    	}else {
    		
    		if ( _11870Layer.class.isInstance(getMyLayer()) )
            {
                _11870Layer layer = (_11870Layer) getMyLayer();

        		showDialog(DIALOG_PBAR);
                layer.getThreadtoUpdate (handlerEnd, strCategories).start();
            }
            else if (LibreGeoSocialLayer.class.isInstance(getMyLayer()))
            {
                LibreGeoSocialLayer layer = (LibreGeoSocialLayer) getMyLayer();

        		showDialog(DIALOG_PBAR);
                layer.getThreadtoUpdate (handlerEnd, strCategories).start();
            }else if (NodeListLayer.class.isInstance(getMyLayer()))
            {
                NodeListLayer layer = (NodeListLayer) getMyLayer();

        		showDialog(DIALOG_PBAR);
                layer.getThreadtoUpdate (handlerEnd, strCategories).start();
            }else if ( PanoramioLayer.class.isInstance(getMyLayer()) )
            {
                PanoramioLayer layer = (PanoramioLayer) getMyLayer();

        		showDialog(DIALOG_PBAR);
                layer.getThreadtoUpdate (handlerEnd, strCategories).start();
            }

//        	cubeList.resetList(resourceList.size());
    	}
    }
	
    protected void onPause(){
    	super.onPause();
//    	orListener.stopAudio();
    	compassManager.unregisterListeners();
    	if(!(idGPS<0))
    			LocationService.unRegisterLocationListener(idGPS);

		LibreGeoSocial.getInstance().setUserPosition((double) getLocation()[0], (double) getLocation()[1], (double) altitude);
		
		Location loc = new Location("Manual");
		loc.setLatitude(getLocation()[0]);
		loc.setLongitude(getLocation()[1]);
		loc.setAltitude(altitude);
		LocationService.setCurrentLocation(loc);
		
//		if(opengl != null)
//			opengl.onPause();
    }
    
    protected void onResume(){
    	super.onResume();
    	refreshed = false;
    	showMenu = true;
//    	if(opengl != null)
//			opengl.onResume();
    	
    	getLayers().cleanResouceLayer();
    	getLayers().cleanExtraLayer();
    	showResources();
    	compassManager.setOnCompassChangeListener(compassListener);
		
    	if(!(idGPS<0))
    		idGPS = LocationService.registerLocationListener(locationListener);
    	
    }
    
    protected void onDestroy(){
    	
    	this.mWakeLock.release();
    	super.onDestroy();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	
    	if(LibreGeoSocialLayer.class.isInstance(getMyLayer())){
    		SubMenu sub0 = menu.addSubMenu(0, MENU_TAGGING, 0, "Tag resource")
    			.setIcon(R.drawable.tag);
    		sub0.add(0,MENU_TAGGING_IMMEDIATE, 0, "Immediate");
    		sub0.add(0,MENU_TAGGING_FAST, 0, "Fast");
    		sub0.add(0,MENU_TAGGING_MAP, 0, "Map");
    		sub0.add(0,MENU_TAGGING_ACCURATE_SIDE, 0, "Accurate side");
    		sub0.add(0,MENU_TAGGING_ACCURATE_LINE, 0, "Accurate line");
//    		sub0.add(0,MENU_TAGGING_ANGLE, 0, "Angular");

    		menu.add(0, MENU_DISTANCE_FILTER, 0, "Distance filter")
    			.setIcon(R.drawable.meter);
    	}

//		menu.add(0, MENU_COMPASS_CORRECTION, 0, "Azim dev.");
    	
    	SubMenu sub1 = menu.addSubMenu(0, MENU_LOCATION, 0, "Location")
    		.setIcon(R.drawable.mundo);
    	sub1.add(0,MENU_INDOOR_LOCATION, 0, "BIDI Location");
    	sub1.add(0,MENU_SERVICE_LOCATION, 0, "Location service");
    	sub1.add(0,MENU_LOCATION_WAYS, 0, "Manual");
    	
    	menu.add(0, MENU_PREFERENCES, 0, "Settings")
    		.setIcon(R.drawable.spanner_48);
    	
        super.onCreateOptionsMenu(menu);        
        return true;
    }

    public boolean onOptionsItemSelected (MenuItem item) {
    	
    	if(showMenu){
    		//FIXME testing line
    		TestingManager.setInitTime();
    		
    		switch (item.getItemId()) {

    		case MENU_DISTANCE_FILTER:
    			View view = CustomViews.createSeekBar(this, 50, getMyLayer().getDistance(), "Km.", distFiltClickListener);

    			getLayers().addExtraElement(view, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
    			
    			showMenu = false;
    			break;
    			
//    		case MENU_COMPASS_CORRECTION:
//
//    			getLayers().addExtraElement(compassManager.getCorrectionSeekbar(this, acceptCorrection), 
//    					new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
//    			
//    			showMenu = false;
//    			break;
    			
    		case MENU_SERVICE_LOCATION:
    			if(idGPS==-1)
    				idGPS = LocationService.registerLocationListener(locationListener);
    			else{
    				LocationService.unRegisterLocationListener(idGPS);
    				idGPS = -1;
    			}
    			break;
    			
    		case MENU_INDOOR_LOCATION:
    			getLayers().cleanResouceLayer();
    			PackageManager pm = getPackageManager();
    			List<ApplicationInfo> list = pm.getInstalledApplications(PackageManager.GET_META_DATA);
    			boolean isBarcode = false;
    			for(int i = 0; i< list.size(); i++){
    				if( list.get(i).packageName.equals("com.google.zxing.client.android")){
    					isBarcode = true;
    					break;
    				}
    			}

    			if (!isBarcode){
    				Toast.makeText(getBaseContext(), 
    						"Please, install Barcode Scanner from Market",
    						Toast.LENGTH_LONG).show();
    				break;
    			}

    			Intent intent = new Intent("com.google.zxing.client.android.SCAN");
    			intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
    			startActivityForResult(intent, BIDI_LOC);
    			break;
    			
    		case MENU_LOCATION_WAYS:
    			Intent intent1 = new Intent(this, LocationWays.class);
    			startActivityForResult(intent1, LOC_WAYS);
    			break;
    			
    		case MENU_TAGGING_IMMEDIATE:
    			
    			tagManager.setSavingType(ARTagManager.TAG_IMMEDIATE);
    			showMenu = false;
    			break;
    			
    		case MENU_TAGGING_FAST:

    			tagManager.setSavingType(ARTagManager.TAG_FAST);
    			showMenu = false;
    			break;

    		case MENU_TAGGING_MAP:

    			tagManager.setSavingType(ARTagManager.TAG_MAP);
    			showMenu = false;
    			break;
    			
    		case MENU_TAGGING_ACCURATE_SIDE:
    			tagManager.setSavingType(ARTagManager.TAG_ACCURATE_SIDE);
    			showMenu = false;
    			
    			break;
    			
    		case MENU_TAGGING_ACCURATE_LINE:
    			tagManager.setSavingType(ARTagManager.TAG_ACCURATE_LINE);
    			showMenu = false;
    			break;
    			
    		case MENU_TAGGING_ANGLE:
    			tagManager.setSavingType(ARTagManager.TAG_ANGLE);
    			showMenu = false;
    			break;
    			
    		case MENU_PREFERENCES:
    			getLayers().cleanResouceLayer();
    			Intent i = new Intent(this, ARPreferences.class);
        		startActivityForResult(i, MENU_PREFERENCES);
    			break;
    		}
    		
    	}else
    		Toast.makeText(getBaseContext(), 
					   "Please, finish your action.",
					   Toast.LENGTH_LONG).show();
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {       
    	
    	switch (id) {
    	case DIALOG_PBAR:
    		ProgressDialog dialog = new ProgressDialog(this);
    		dialog.setMessage("Loading...");
    		dialog.setIndeterminate(true);
    		dialog.setCancelable(true);
    		return dialog;
    		
    	case DIALOG_NOHEIGHT:
    		return new AlertDialog.Builder(this)
    		.setTitle("Warning")
    		.setMessage("Some resources don't have information about height")
    		.setPositiveButton("Download it!", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					action = ACTION_REQUEST;
					actionRequestHeight();
				}
			})
			.setNeutralButton("No heights",new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					action = ACTION_NOHEIGHT;
					useHeight(false);
				}
			})
			.setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					action = ACTION_IGNORE;
				}
			})
			.create();
    		
    	case DIALOG_MOVE:

    		LayoutInflater factory1 = LayoutInflater.from(this);
    		final View textEntryView1 = factory1.inflate(R.layout.dialog_movement, null);

    		OnClickListener moveStraightListener = new OnClickListener(){
    			
    			public void onClick(View v) {
    				setLocation(LocationUtils.moveTo(tagManager.getUserLocation(), ARCompassManager.getAzimuth(tagManager.getAngles()), 
    						LocationUtils.MOVE_STRAIGHT, 1));

    				tagManager.setUserLocation(getLocation());
    				dismissDialog(DIALOG_MOVE);
    			}

    		};

    		OnClickListener moveRightListener = new OnClickListener(){
    			
    			public void onClick(View v) {
    				setLocation(LocationUtils.moveTo(tagManager.getUserLocation(), ARCompassManager.getAzimuth(tagManager.getAngles()), 
    						LocationUtils.MOVE_RIGHT, 1));

    				tagManager.setUserLocation(getLocation());
    				dismissDialog(DIALOG_MOVE);
    			}

    		};

    		OnClickListener moveBackListener = new OnClickListener(){
    			
    			public void onClick(View v) {
    				setLocation(LocationUtils.moveTo(tagManager.getUserLocation(), ARCompassManager.getAzimuth(tagManager.getAngles()), 
    						LocationUtils.MOVE_BACK, 1));

    				tagManager.setUserLocation(getLocation());
    				dismissDialog(DIALOG_MOVE);
    			}

    		};

    		OnClickListener moveLeftListener = new OnClickListener(){
    			
    			public void onClick(View v) {
    				setLocation(LocationUtils.moveTo(tagManager.getUserLocation(), ARCompassManager.getAzimuth(tagManager.getAngles()), 
    						LocationUtils.MOVE_LEFT, 1));

    				tagManager.setUserLocation(getLocation());
    				dismissDialog(DIALOG_MOVE);
    			}

    		};

    		Button btnStraight = (Button) textEntryView1.findViewById (R.id.btMoveStraight);
    		btnStraight.setClickable(true);
    		btnStraight.setOnClickListener(moveStraightListener);

    		Button btnBack = (Button) textEntryView1.findViewById (R.id.btMoveBack);
    		btnBack.setClickable(true);
    		btnBack.setOnClickListener(moveBackListener);

    		Button btnLeft = (Button) textEntryView1.findViewById (R.id.btMoveLeft);
    		btnLeft.setClickable(true);
    		btnLeft.setOnClickListener(moveLeftListener);

    		Button btnRight = (Button) textEntryView1.findViewById (R.id.btMoveRight);
    		btnRight.setClickable(true);
    		btnRight.setOnClickListener(moveRightListener);

    		if(idGPS!=-1){
    			btnLeft.setVisibility(View.INVISIBLE);
    			btnRight.setVisibility(View.INVISIBLE);
    			btnStraight.setVisibility(View.INVISIBLE);
    			btnBack.setVisibility(View.INVISIBLE);
    		}

    		if(tagManager.getSavingType() == ARTagManager.TAG_ACCURATE_LINE){
    			btnLeft.setVisibility(View.INVISIBLE);
    			btnRight.setVisibility(View.INVISIBLE);

    		}else{
    			btnStraight.setVisibility(View.INVISIBLE);
    			btnBack.setVisibility(View.INVISIBLE);
    		}

    		return new AlertDialog.Builder(this)	      
    		.setCancelable(false)
    		.setTitle("Move for tagging")
    		.setView(textEntryView1)
    		.setPositiveButton("Done", new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int whichButton) {

    				/* User clicked OK so do some stuff */ 
    				showMenu = true;
    				getLayers().cleanExtraLayer();
    				tagManager.launchResult();
    				removeDialog(DIALOG_MOVE);

    			}
    		})
    		.setNeutralButton("Skip", new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int whichButton) {

    				/* User clicked OK so do some stuff */ 

    			}
    		})
    		.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int whichButton) {

    				/* User clicked OK so do some stuff */ 
    				showMenu = true;
    				tagManager.setSavingType(-1);

    				getLayers().cleanExtraLayer();
    				removeDialog(DIALOG_MOVE);
    			}
    		})
    		.create();
    	}
		return null;
    
	}
    
    private void actionRequestHeight(){
    	final Handler handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				refreshed = true;
				removeDialog(DIALOG_PBAR);
			}
		};
		refreshed = false;
		removeDialog(DIALOG_NOHEIGHT);
		useHeight(true);
		showDialog(DIALOG_PBAR);
		new Thread(){
			public void run(){
				updateHeights();
				handler.sendEmptyMessage(0);
			}
		}.start();
    }

    
	protected void onActivityResult (int requestCode, int resultCode, Intent data) { 
		switch (requestCode) { 
		
    		
	    	case ARTagManager.TAG_MAP:
	    		
	    		if( resultCode != Activity.RESULT_CANCELED ) {
	    			
	    			float[] location = {data.getFloatExtra("RES_LATITUDE", 0), data.getFloatExtra("RES_LONGITUDE", 0), 0};
	    			tagManager.setResourceLocation(location);
	    			
	    			tagManager.launchResult();	    		
	    		} else
	    			Toast.makeText(getBaseContext(), 
            				"Map tagging canceled", 
            				Toast.LENGTH_LONG).show();
	    		
	    		break;
	    		
	    	case BIDI_LOC:
	    		
	    		if( resultCode != Activity.RESULT_CANCELED ){
		    		String contents = data.getStringExtra("SCAN_RESULT");
	    			try{
	    				String[] info = contents.split(";");
	    				float[] location = {Float.parseFloat(info[0]), Float.parseFloat(info[1]), 
	        					0};
	    				setLocation(location);
	    				altitude = Float.parseFloat(info[2]);
	    				cam_altitude = AltitudeManager.getAbsoluteAltitude(this, altitude, false);
	    				LocationUtils.setUserHeight(cam_altitude);
	        			tagManager.setUserLocation(location);
	        			tagManager.setCamAltitude(cam_altitude);
	    			}catch(Exception e){
	    				Toast.makeText(getBaseContext(), 
	    						"There was an error with BIDI location", 
	    						Toast.LENGTH_LONG).show();
	    			}
	    		}else
	    			Toast.makeText(getBaseContext(), 
	    					"There was an error with BIDI location", 
	    					Toast.LENGTH_LONG).show();
	    		
	    		break;
	    		
	    	case LOC_WAYS:
    			float[] location = {(float) LocationService.getCurrentLocation().getLatitude(), 
    					(float) LocationService.getCurrentLocation().getLongitude(), 
    					0};
    			setLocation(location);
				altitude = (float) LocationService.getCurrentLocation().getAltitude();
				cam_altitude = AltitudeManager.getAbsoluteAltitude(getBaseContext(), altitude, true);
				LocationUtils.setUserHeight(cam_altitude);

    			tagManager.setUserLocation(location);
    			tagManager.setCamAltitude(cam_altitude);
	    		break;
	    		
	    	case MENU_PREFERENCES:
	    		cam_altitude = AltitudeManager.getAbsoluteAltitude(this, altitude, true);
	    		LocationUtils.setUserHeight(cam_altitude);
    			tagManager.setCamAltitude(cam_altitude);
	    		
    			if(loadMainHeightPreference())
    				loadThresholdPreferences();
    			
	    		SharedPreferences sharedPreferences = 
					PreferenceManager.getDefaultSharedPreferences(ARView.this);
//				if(sharedPreferences.getBoolean(ARPreferences.KEY_MOVEMENT_LINE, false)){
//					if(mPath == null){
//						mPath = new DrawPath(this);
//						getLayers().addInfoElement(mPath, null);
//					}
//				}else{
//					if(mPath!=null){
//						getLayers().removeInfoElement(mPath);
//						mPath = null;
//					}
//				}
				
				if(sharedPreferences.getBoolean(ARPreferences.KEY_MEASURES, false)){
					if(mParameters == null){
						mParameters = new DrawParameters(this);
						getLayers().addInfoElement(mParameters, null);
					}
				}else{
					if(mParameters!=null){
						getLayers().removeInfoElement(mParameters);
						mParameters = null;
					}
				}
				
				getLayers().setMoveSummary(sharedPreferences.getBoolean(ARPreferences.KEY_MOVE_LABELS, false));
				
	    		break;
	    	
	
            default:
                break; 
		}
	}
	
	private Handler handlerEnd = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(ARView.this.isFinishing())
				return;
			load_list = false;
			showResources();
			removeDialog(DIALOG_PBAR);
		}
	};
	

	public static void GestureNext ()
	{		
		if (pointerObject == null)
			return;
		
		ARLayerManager layers = pointerObject.getLayers();
		int num_click = layers.getNodeClicked();
		if(num_click < 0)
			return;
		int fixed_num = num_click;
		do{
			num_click++;
			if(num_click >= pointerObject.getResourcesList().size())
				num_click = 0;
			if(fixed_num == num_click)
				break;
		}while(!pointerObject.getResourcesList().get(num_click).getDrawn().forceClick());
		
		Log.e("Gesture", "NEXT " + Integer.toString(num_click));
		return ;
		
	}
	
	public static void GesturePrevious ()
	{	
		if (pointerObject == null)
			return;
		
		ARLayerManager layers = pointerObject.getLayers();
		int num_click = layers.getNodeClicked();
		if(num_click < 0)
			return;
		int fixed_num = num_click;
		do{
			num_click--;
			if(num_click < 0)
				num_click = pointerObject.getResourcesList().size() - 1;
			if(fixed_num == num_click)
				break;
		}while (!pointerObject.getResourcesList().get(num_click).getDrawn().forceClick());
		
		Log.e("Gesture", "PREVIOUS " + Integer.toString(num_click));
		return;
	}
}
